using OpenPms.Data;

using System.Text;

using static System.Runtime.InteropServices.JavaScript.JSType;

namespace OpenPms.Areas.M.Pages.Setup.Rate;

public class EditPriceDetailModel : PageModel
{
    private readonly Data.AppDbContext db;
    public EditPriceDetailModel(Data.AppDbContext db)
    {
        this.db = db;
    }
    public ERateType RateType { get => TempData.Peek<ERateType>(ETempDataKey.RateType); }
    public string? RateName { get => TempData.Peek<string>(ETempDataKey.RateName); }
    public Guid RateId { get => TempData.Peek<Guid>(ETempDataKey.RateId); }
    public bool IsDelayPrice { get => TempData.Peek<bool>(ETempDataKey.IsDelayPrice); }
    [BindProperty]
    public TPrice Item { get; set; } = default!;
    [BindProperty]
    public List<TPrice> Items { get; set; } = default!;

    public async Task<IActionResult> OnGetAsync(int dayNumber)
    {
        var roomTypeItems = await db.RoomTypes.Where(ii => ii.HotelId == User.GetExtId()).OrderBy(ii => ii.Name).ToListAsync();
        if (dayNumber == 0)
        {
            Item = new TPrice { Date = DateOnly.FromDateTime(DateTime.Today.AddMonths(1)) };
            Items = new();
        }
        else
        {
            Item = new TPrice { Date = DateOnly.FromDayNumber(dayNumber) };
            Items = await db.Prices.Include(ii => ii.RoomType).Where(ii => ii.RateId == RateId && ii.Date == Item.Date).ToListAsync();
        }

        var needAddRoomTypeItems = roomTypeItems.ExceptBy(Items.Select(ii => ii.RoomTypeId), ii => ii.Id).ToList();
        if (needAddRoomTypeItems.Count > 0)
            Items.AddRange(needAddRoomTypeItems.Select(ii => new TPrice
            {
                RoomType = ii,
                RoomTypeId = ii.Id,
            }));
        Items.ForEach(ii => ii.SetRoomType());
        Items = Items.OrderBy(ii => ii.RoomTypeName).ToList();
        return Page();

    }



    public async Task<IActionResult> OnPostAsync()
    {
        try
        {
            await db.Prices.Where(ii => ii.RateId == RateId && ii.Date == Item.Date).ExecuteDeleteAsync();
            foreach (var ii in Items)
            {
                ii.RateId = RateId;
                ii.Date = Item.Date;
                db.Prices.Add(ii);
            }
            await db.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.ToString());
            return Page();

        }
        return RedirectToPage("./EditPrice");

    }



    public async Task<IActionResult> OnPostDeleteAsync()
    {
        await db.Prices.Where(ii => ii.RateId == RateId && ii.Date == Item.Date).ExecuteDeleteAsync();
        return RedirectToPage("./EditPrice");
    }
}
